<template>
  <!-- 添加文章 -->
  <div class="add-article">
    <div class="main">
      <div class="editor">
        <el-form :inline="true" class="form" :rules="rules" ref="formRef" :model="article">
          <el-form-item>
            <span style="font-size: 18px; font-weight: 600">添加文章</span>
          </el-form-item>
          <el-form-item style="margin-left: 55vw">
            <el-button type="primary" @click="submit(0)">提交</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="submit(3)">暂存为草稿</el-button>
          </el-form-item>
          <el-form-item label="文章标题" prop="title">
            <el-input placeholder="请输入文章标题" v-model="article.title"></el-input>
          </el-form-item>
          <el-form-item label="文章分类" prop="categoryId">
            <el-select placeholder="请选择文章分类" v-model="article.categoryId">
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标签">
            <el-select placeholder="请选择标签" clearable @change="selectAddTag">
              <el-option
                v-for="item in tagList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <div class="tags">
              <el-tag
                v-for="item in article.tags || []"
                :key="item.id"
                closable
                :disable-transitions="false"
                @close="handleClose(item.name)"
                >{{ item.name }}</el-tag
              >
              <el-input
                v-if="inputVisable"
                ref="inputRef"
                v-model="inputTagValue"
                @keyup.enter="handleInputConfirm"
                @blur="handleInputConfirm"
              ></el-input>
              <el-button v-else size="small" @click="addTag">+ 新增标签</el-button>
            </div>
          </el-form-item>
          <el-form-item prop="content">
            <TextEditor v-model="article.content" />
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import TextEditor from '@/components/TextEditor.vue'
import { nextTick, onMounted, ref } from 'vue'
import { getTagsListService } from '@/api/Tags'
import { getCategoryListService } from '@/api/Category'
import { addArticle, getArticleById, updateArticleById } from '@/api/Articles'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

// 接收路由传递的参数id
const id = ref('')
id.value = route.params.id

const formRef = ref()

// 后端返回的标签数据
const tagList = ref([])
// 后端返回的分类数据
const categoryList = ref([])
// 传递给后端的参数
const article = ref({
  id: null,
  title: '',
  content: '',
  categoryId: null,
  tags: [],
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
  content: [{ required: true, message: '文章内容不能为空', trigger: 'blur' }],
}

/**
 * 关闭标签
 */
const handleClose = (name) => {
  let index = -1
  for (let i = 0; i < article.value.tags.length; i++) {
    if (article.value.tags[i].name === name) {
      index = i
    }
  }
  if (index !== -1) {
    article.value.tags.splice(index, 1)
  }
}

const inputRef = ref()
const inputVisable = ref(false)
const inputTagValue = ref('')
/**
 * 插入标签
 */
const handleInputConfirm = () => {
  if (inputTagValue.value.length > 10 || inputTagValue.value.length < 2) {
    ElMessage.warning('标签名长度在2-5之间')
    inputVisable.value = false
    return
  }
  if (inputTagValue.value) {
    const tag = {
      name: inputTagValue.value,
    }
    article.value.tags.push(tag)
  }
  inputVisable.value = false
}
const addTag = () => {
  if (article.value.tags.length === 3) {
    ElMessage.warning('标签数量已达上限')
    return
  }
  inputVisable.value = true
  nextTick(() => {
    inputRef.value.input.focus()
  })
  inputTagValue.value = ''
}

/**
 * 在下拉框选择添加标签
 */
const selectAddTag = (id) => {
  if (article.value.tags.length === 3) {
    ElMessage.warning('标签数量已达上限')
    return
  }
  const selectTag = tagList.value.find((item) => {
    if (item.id === id) {
      return item.name
    }
  })
  if (selectTag) {
    article.value.tags.push({ name: selectTag.name })
  }
}

/**
 * 获取所有标签信息
 */
const getTags = async () => {
  const { data } = await getTagsListService()
  tagList.value = data
}

/**
 * 获取所有分类信息
 */
const getCategory = async () => {
  const { data } = await getCategoryListService()
  categoryList.value = data
}

/**
 * 提交
 * @param status
 */
const submit = (status) => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 文章内容非空判断
      if (article.value.content === '<p><br></p>') {
        ElMessage.error('文章内容信息不能为空')
        return false
      }
      // 判断是修改还是新增
      console.log('路由id', article.value.id)
      if (article.value.id == -1) {
        console.log('新增文章')
        const res = await addArticle(status, article.value)
        if (res.code === 0) {
          ElMessage.error('添加失败')
        } else {
          router.back(-1)
        }
      } else {
        console.log('修改文章')
        const res = await updateArticleById(status, article.value)
        console.log(res)
        if (res.code === 0) {
          ElMessage.error('修改失败')
        } else {
          router.back(-1)
        }
      }
    } else {
      ElMessage.error('提交失败请检查是否漏填')
      return false
    }
  })
}
const getArticle = async (id) => {
  console.log('当前id为', id)
  article.value.id = id
  if (id != -1) {
    const { data } = await getArticleById(id)
    article.value = data
    return
  }
}
onMounted(() => {
  getTags()
  getCategory()
  getArticle(id.value)
})
</script>

<style lang="scss" scoped>
* {
  border: none !important;
}
.add-article {
  height: 100vh;
  background-color: #f3f4f5;
  padding: 15px;

  .main {
    height: 100vh;
    padding: 20px;
    background-color: #fff;
    border-radius: 7px;

    .editor {
      .form {
        .tags {
          display: flex;
          gap: 10px;
          align-items: center;

          :deep(.el-input) {
            width: 60px;
            height: 24px;
          }
        }

        :deep(.el-select__wrapper) {
          width: 150px;
        }
      }
    }
  }
}
::v-deep .w-e-scroll {
  scrollbar-width: none;
}
</style>